# Excel剪贴板操作模块
# 实现识别Excel中用户所选中的单元格，并将这些单元格的值复制到系统剪贴板的功能

import win32com.client
import pyperclip
import traceback

class ExcelClipboardManager:
    def __init__(self):
        """初始化Excel剪贴板管理器"""
        self.excel_app = None
        
    def connect_to_excel(self):
        """连接到正在运行的Excel应用程序"""
        try:
            # 尝试获取已运行的Excel实例
            self.excel_app = win32com.client.GetActiveObject('Excel.Application')
            return True
        except Exception as e:
            print(f"连接Excel失败: {e}")
            print(traceback.format_exc())
            return False
    
    def get_selected_cells(self):
        """获取用户在Excel中选中的单元格"""
        try:
            if not self.excel_app:
                if not self.connect_to_excel():
                    return None
            
            # 获取当前选中的范围
            selection = self.excel_app.Selection
            if not selection:
                print("未选中任何单元格")
                return None
            
            # 获取选中范围的所有单元格值
            selected_values = []
            
            # 检查是否是单个单元格
            if selection.Cells.Count == 1:
                cell_value = selection.Value
                if cell_value is not None:
                    selected_values.append(str(cell_value))
            else:
                # 遍历选中的单元格范围
                for row in selection.Rows:
                    row_values = []
                    for cell in row.Cells:
                        cell_value = cell.Value
                        if cell_value is not None:
                            row_values.append(str(cell_value))
                        else:
                            row_values.append("")
                    # 将一行的值用制表符连接
                    selected_values.append('\t'.join(row_values))
            
            return selected_values
        except Exception as e:
            print(f"获取选中单元格失败: {e}")
            print(traceback.format_exc())
            return None
    
    def copy_selected_cells_to_clipboard(self):
        """将Excel中选中的单元格值复制到系统剪贴板"""
        try:
            # 获取选中单元格的值
            selected_values = self.get_selected_cells()
            if not selected_values:
                print("没有获取到选中的单元格值")
                return False
            
            # 将选中的值转换为文本并复制到剪贴板
            text_to_copy = '\n'.join(selected_values)
            pyperclip.copy(text_to_copy)
            
            print(f"已成功复制{len(selected_values)}个单元格值到剪贴板")
            return True
        except Exception as e:
            print(f"复制到剪贴板失败: {e}")
            print(traceback.format_exc())
            return False
    
    def copy_selected_cells_as_list(self):
        """将Excel中选中的单元格值复制为列表形式到剪贴板"""
        try:
            # 获取选中单元格的值
            selected_values = self.get_selected_cells()
            if not selected_values:
                print("没有获取到选中的单元格值")
                return False
            
            # 移除制表符，将所有值放在同一列表中
            flat_values = []
            for row in selected_values:
                # 如果行包含制表符，分割成多个值
                if '\t' in row:
                    flat_values.extend(row.split('\t'))
                else:
                    flat_values.append(row)
            
            # 将值转换为文本并复制到剪贴板
            text_to_copy = '\n'.join(flat_values)
            pyperclip.copy(text_to_copy)
            
            print(f"已成功复制{len(flat_values)}个单元格值（列表形式）到剪贴板")
            return True
        except Exception as e:
            print(f"复制为列表形式到剪贴板失败: {e}")
            print(traceback.format_exc())
            return False
    
    def close(self):
        """关闭Excel连接"""
        try:
            if self.excel_app:
                # 释放Excel对象
                self.excel_app = None
                print("已关闭Excel连接")
        except Exception as e:
            print(f"关闭Excel连接时出错: {e}")

# 示例用法
if __name__ == "__main__":
    try:
        # 创建Excel剪贴板管理器实例
        excel_manager = ExcelClipboardManager()
        
        # 复制选中的单元格值到剪贴板
        success = excel_manager.copy_selected_cells_to_clipboard()
        if success:
            print("操作完成！请在其他应用程序中粘贴查看结果。")
        else:
            print("操作失败！")
        
        # 关闭连接
        excel_manager.close()
    except Exception as e:
        print(f"执行过程中发生错误: {e}")
        print(traceback.format_exc())